package com.example.googlemapdrawroutelast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;

public class GetRouteById extends AsyncTask<Integer, Void, RouteInfo>{

		private View view;
		

		public GetRouteById(View view) {
			super();
			this.view = view;
			
		}

		@Override
		protected RouteInfo doInBackground(Integer... params) {
			try {
				String strUrl = "http://" + UrlClass.getUrl() + "/v1/route/"
						+ params[0].toString();
				URL url = new URL(strUrl);
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setConnectTimeout(15000);
				connection.setReadTimeout(15000);
				connection.setRequestMethod("GET");
				connection.setDoOutput(true);

				InputStream iStream = connection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(iStream));

				StringBuffer sb = new StringBuffer();
				String line = "";

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				iStream.close();

				String jsonResponseString = sb.toString();
				JSONObject jsonResponse = new JSONObject(jsonResponseString);
				RouteInfo routeInfo = new RouteInfo(
						jsonResponse.getInt("id_route"),
						jsonResponse.getString("name_route"),
						jsonResponse.getString("description"),
						jsonResponse.getString("coordinates"),
						jsonResponse.getString("characteristicPoints"),
						jsonResponse.getInt("id_user"));

				return routeInfo;

			} catch (Exception e) {
				e.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(RouteInfo route) {
			super.onPostExecute(route);
			Intent intent = new Intent(view.getContext(), MainActivity.class);
			intent.putExtra("route", route);
			intent.putExtra("isRouteView", true);
			//activity.startActivityForResult(intent, 0);
		}

}

